import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/util/customer_dialog.dart';

// 输入框高度百分比
const double _scale = 0.7;
// 提示百分比
const double _tipScale = 0.2;
// 文字占用输入框的比例
const double _textFontHeightScale = 0.5;
// 文字占用输入框的比例
const double _textFontSizeScale = 0.3;
// 文字行高
const double _textHeight = 1.0;

class ITextFiled extends StatefulWidget {
  final String? hintText;
  final IconData? preIcon;
  final double? iTextWidth;
  final double iTextHeight;
  final bool? obscureText;
  final String? defaultStr;
  // 是否需要显示错误信息 如果开启后输入框的高度只有70%
  final bool showError;
  final BoxDecoration? inputDecoration;
  final TextFiledValidata? textFiledValidata;
  const ITextFiled(this.iTextWidth, this.iTextHeight,
      {super.key,
      this.obscureText = false,
      this.hintText,
      this.preIcon,
      this.textFiledValidata,
      this.defaultStr,
      this.showError = true,
      this.inputDecoration});
  @override
  ITextFiledState createState() => ITextFiledState();
}

class ITextFiledState extends State<ITextFiled> {
  final TextEditingController _textEditingController =
      TextEditingController(text: "");
  final FocusNode _focusNode = FocusNode();
  double maxHeight = 0;
  double inputHeight = 0;
  BoxDecoration? _inputDecoration;
  OverlayEntry? _overlayEntry;
  @override
  void initState() {
    // 当没有error 信息的时候  直接铺满 整个widget
    if (widget.showError) {
      maxHeight = widget.iTextHeight * _scale;
      inputHeight = widget.iTextHeight * _scale;
    } else {
      maxHeight = widget.iTextHeight;
      inputHeight = widget.iTextHeight;
    }
    if (widget.inputDecoration == null) {
      _inputDecoration = BoxDecoration(
        color: Colors.black.withOpacity(0.1),
      );
    } else {
      _inputDecoration = widget.inputDecoration;
    }
    _textEditingController.text = widget.defaultStr!;
    _textEditingController.addListener(() {
      if (widget.textFiledValidata != null) {
        widget.textFiledValidata!.error = null;
      }
      setState(() {});
    });
    if (widget.textFiledValidata != null) {
      if (widget.defaultStr != null && widget.defaultStr != "") {
        widget.textFiledValidata!.show = true;
        widget.textFiledValidata!.value = widget.defaultStr;
        widget.textFiledValidata!.success =
            RegExp(widget.textFiledValidata!.paretten!)
                .hasMatch(widget.defaultStr!);
      }
    }
    super.initState();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _focusNode.unfocus();
        showCustomInput();
      } else {}
    });
  }

  void showCustomInput() {
    TextEditingController floatTec =
        TextEditingController(text: _textEditingController.text);
    FocusNode floatTfn = FocusNode();

    void closeInput() {
      CustomerDialog.closeAllLoading(groupKey: CustomerDialog.INPUT_GROUP);
    }

    floatTfn.addListener(() {
      if (!_focusNode.hasFocus) {
        /*  _floatTfn.unfocus();
        _focusNode.unfocus();
        _overlayEntry?.remove();
        _overlayEntry = null;
        closeInput(); */
      }
    });

    void initData() {
      floatTfn.unfocus();
      _textEditingController.text = floatTec.text;
      if (null != widget.textFiledValidata) {
        widget.textFiledValidata!.show = true;
        if (null != widget.textFiledValidata!.paretten) {
          widget.textFiledValidata!.success =
              RegExp(widget.textFiledValidata!.paretten!)
                  .hasMatch(floatTec.text);
        }
        widget.textFiledValidata!.value = floatTec.text;
      }
      CustomerDialog.closeAllLoading(groupKey: CustomerDialog.INPUT_GROUP);
    }

    CustomerDialog.showGamingDialog(
        (cancel) => Stack(
              children: [
                Positioned(
                  top: MediaQuery.of(context).viewInsets.bottom,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Column(
                    children: [
                      Material(
                        child: Container(
                          padding: EdgeInsets.all(widget.iTextHeight / 10),
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: const Color.fromARGB(
                                      255, 105, 164, 247))),
                          height: 40.h,
                          child: TextField(
                            autofocus: false,
                            autocorrect: true,
                            minLines: 1,
                            enableInteractiveSelection: false,
                            obscureText: widget.obscureText!,
                            focusNode: floatTfn,
                            controller: floatTec,
                            textAlignVertical: TextAlignVertical.bottom,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.only(bottom: 10.h),
                              hintText: widget.hintText,
                              border: const OutlineInputBorder(
                                  borderSide: BorderSide.none),
                              hintStyle: TextStyle(
                                  textBaseline: TextBaseline.alphabetic,
                                  height: 1,
                                  fontSize: 20.h),
                            ),
                            style: TextStyle(height: 1.0, fontSize: 20.h),
                            onSubmitted: (val) {
                              initData();
                            },
                            onChanged: (val) {
                              if (null != widget.textFiledValidata &&
                                  null != widget.textFiledValidata!.paretten) {
                                widget.textFiledValidata!.show = true;
                                if (null !=
                                    widget.textFiledValidata!.paretten) {
                                  widget.textFiledValidata!.success = RegExp(
                                          widget.textFiledValidata!.paretten!)
                                      .hasMatch(val);
                                }
                              }
                              widget.textFiledValidata!.value = val;
                              _textEditingController.text = val;
                            },
                          ),
                        ),
                      ),
                      Expanded(
                          child: GestureDetector(
                              onTap: () {
                                floatTfn.unfocus();
                                _focusNode.unfocus();
                                _overlayEntry?.remove();
                                _overlayEntry = null;
                                closeInput();
                              },
                              child: Container(
                                color: Colors.grey.withOpacity(0.3),
                              )))
                    ],
                  ),
                )
              ],
            ),
        groupKey: CustomerDialog.INPUT_GROUP);
    // 聚焦到输入框
    floatTfn.requestFocus();
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode.dispose();
    _textEditingController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 这里  要判断是否显示error 如果不显示
    return Container(
      constraints: BoxConstraints(
          maxHeight: widget.iTextHeight, maxWidth: widget.iTextWidth!),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.zero,
            decoration: _inputDecoration,
            margin: EdgeInsets.zero,
            child: ConstrainedBox(
                constraints: BoxConstraints(
                    maxHeight: inputHeight,
                    minHeight: inputHeight,
                    maxWidth: widget.iTextWidth!),
                child: TextField(
                  autofocus: false,
                  autocorrect: true,
                  enableInteractiveSelection: false,
                  obscureText: widget.obscureText!,
                  focusNode: _focusNode,
                  controller: _textEditingController,
                  textCapitalization: TextCapitalization.characters,
                  textAlignVertical: TextAlignVertical.center,
                  style: TextStyle(
                      fontSize: inputHeight * _textFontHeightScale, height: 1),
                  decoration: InputDecoration(
                    prefixIcon: null != widget.preIcon
                        ? Icon(
                            widget.preIcon,
                            size: inputHeight * _textFontHeightScale,
                          )
                        : null,
                    suffixIcon: _textEditingController.value.text != ""
                        ? InkWell(
                            child: Icon(
                              Icons.clear,
                              color: Colors.red,
                              size: inputHeight * _textFontHeightScale,
                            ),
                            onTap: () {
                              _focusNode.unfocus();
                              _focusNode.canRequestFocus = false;
                              _textEditingController.text = "";
                              widget.textFiledValidata?.value = '';
                              setState(() {});
                            },
                          )
                        : null,
                    /*   isCollapsed: true, */
                    hintText: widget.hintText,
                    hintMaxLines: 1,
                    hintStyle: TextStyle(
                        height: 1.0,
                        fontSize: inputHeight * _textFontHeightScale),
                    fillColor: Colors.black.withOpacity(0.5),
                    contentPadding: EdgeInsets.symmetric(
                        vertical:
                            (inputHeight - inputHeight * _textFontHeightScale) /
                                2),
                    border:
                        const OutlineInputBorder(borderSide: BorderSide.none),
                  ),
                )),
          ),
          widget.showError
              ? Expanded(
                  child: (widget.textFiledValidata != null &&
                              widget.textFiledValidata!.show! &&
                              !RegExp(widget.textFiledValidata!.paretten!)
                                  .hasMatch(_textEditingController.text)) ||
                          (widget.textFiledValidata != null &&
                              null != widget.textFiledValidata!.error)
                      ? Container(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            widget.textFiledValidata!.error != null
                                ? widget.textFiledValidata!.error!
                                : widget.textFiledValidata!.tips!,
                            style: TextStyle(
                                color: Colors.red,
                                height: 1.0,
                                fontSize: widget.iTextHeight * _tipScale),
                            textAlign: TextAlign.right,
                          ))
                      : Container())
              : const SizedBox()
        ],
      ),
    );
  }
}

class TextFiledValidata {
  String? value;
  String? paretten;
  String? tips;
  String? error;
  bool? show;
  bool? success;

  TextFiledValidata();

  bool check() {
    show = true;
    if (success == null) {
      return false;
    }
    return success == true;
  }

  TextFiledValidata.init(
      {this.paretten,
      this.tips,
      this.show = false,
      this.value,
      this.success = false,
      this.error});
}
